/*****  Component, by Ben Bi <prince.bi@gmail.com>  created at: 12/23/2009 4:10:45 PM  *****/

/********   Notes:  *******
 *  Two tags need to be replaced with the module name, they are:
 *  finalClothQcWrapperForm
 *  FinalClothQcWrapperForm
 *  final_cloth_qc_wrapper_form
 *  set panel.id
 */



/***** variables declartion section, begin *****/
var finalClothQcWrapperFormInputMode = wacFormInputMode.add;
var finalClothQcWrapperFormObj = {};
var finalClothQcWrapperFormAuditAction = {};

/***** variables declartion section, end *****/

/***** init section, begin *****/
$(document).ready(
    function() {
        finalClothQcWrapperFormAuditAction = new FinalClothQcWrapperFormAuditAction();

        initFinalClothQcWrapperFormDialog();

        initFinalClothQcWrapperForm();

        bindFinalClothQcWrapperFormEvents();
    }
);

function bindFinalClothQcWrapperFormEvents()
{
    $("#finalClothQcWrapperFormFormDialog").bind('dialogopen', function(event, ui)
    {
        initFinalClothQcWrapperFormData();
//        wacDebugLog("calling " + moduleName + ":" + wacModelObj.finalClothQcWrapperForm.name);//
    });

    $("#finalClothQcWrapperFormFormDialog").bind('dialogclose', function(event, ui)
    {
        $.validationEngine.closePrompt(".formError", true);
    });

    $("#finalClothQcWrapperForm_btnSubmit").bind('click', function (e)
    {
        submitFinalClothQcWrapperForm();
    });

    $("#finalClothQcWrapperForm_btnClose").bind('click', function (e)
    {
        $("#finalClothQcWrapperFormFormDialog").dialog('close');
    });

    // fix dialog div didnt remove bug, remove it by this way
    $('#appStorehouseRightPane').bind('tabsremove', function(event, ui) {
        if(ui.panel.id == "t16502")
        {
            $("div[aria-labelledby='ui-dialog-title-finalClothQcWrapperFormFormDialog']").remove();
            $("#finalClothQcWrapperFormFormDialog").remove();
        }
    });
}


function initFinalClothQcWrapperFormDialog()
{
//    wacDebugLog("initFinalClothQcWrapperFormDialog.");
    $("#finalClothQcWrapperFormFormDialog").dialog({
            bgiframe: true,
            modal: true,
            width: 1050,
            height: 580,
            autoOpen: false,
            buttons: {},
            zIndex: 100
        });
}

function initFinalClothQcWrapperForm()
{
    $("#finalClothQcWrapperFormForm").validationEngine();

    $.datepicker.setDefaults($.datepicker.regional['zh-CN']);
    $("#finalClothQcWrapperForm_qc_date").datepicker({beforeShow: function() {$('#ui-datepicker-div').maxZIndex();}});
    $("#finalClothQcWrapperForm_dispatch_date").datepicker({beforeShow: function() {$('#ui-datepicker-div').maxZIndex();}});
    $("#finalClothQcWrapperForm_goods_return_date").datepicker({beforeShow: function() {$('#ui-datepicker-div').maxZIndex();}});

    $('.wacFormContent .left, .wacFormContent input, .wacFormContent textarea, .wacFormContent select').focus(function(){
        $(this).parents('.wacFormContent').addClass("wacFormOver");
    }).blur(function(){
        $(this).parents('.wacFormContent').removeClass("wacFormOver");
    });

    $('.wacFormContentA .left, .wacFormContentA input, .wacFormContentA textarea, .wacFormContentA select').focus(function(){
        $(this).parents('.wacFormRow').addClass("wacFormOver");
    }).blur(function(){
        $(this).parents('.wacFormRow').removeClass("wacFormOver");
    });


}

function initFinalClothQcWrapperFormData()
{
    wacShowBlockUILoading("#finalClothQcWrapperFormFormDialog");
    $('#finalClothQcWrapperForm_dispatch_order_id, #finalClothQcWrapperForm_roll_unit_code, #finalClothQcWrapperForm_piece_length_unit_code, #finalClothQcWrapperForm_wrap_id').empty();

    var params = {
        "data_format" :'json'
    };

    $.ajax({
        url: BASE_URL + "finalClothQcWrapperForm/getFormData",
        global: true,
        type: "GET",
        data: params,
        dataType: "json",
        success: function(jsonData){
            initFinalClothQcWrapperFormDataCallBack(jsonData);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            wacDebugLog("getFormData Error: " + $(this).dump()); // the options for this ajax request
        }
    });
}

function initFinalClothQcWrapperFormDataCallBack(jsonData)
{
   if(jsonData.info.status == wacOperationStatus.Error)
   {
       alert(jsonData.info.error_info);
   }
   else
    {
        var selectedIndex = 0;

        for(i=0;i<jsonData['items']['unit'].length;i++)
        {
            $('<option value="' + jsonData['items']['unit'][i].key +'">' + jsonData['items']['unit'][i].value +'</option>').appendTo("#finalClothQcWrapperForm_roll_unit_code");
            $('<option value="' + jsonData['items']['unit'][i].key +'">' + jsonData['items']['unit'][i].value +'</option>').appendTo("#finalClothQcWrapperForm_piece_length_unit_code");
        }

        for(i=0;i<jsonData['items']['wrapper'].length;i++)
        {
            $('<option value="' + jsonData['items']['wrapper'][i].key +'">' + jsonData['items']['wrapper'][i].value +'</option>').appendTo("#finalClothQcWrapperForm_wrap_id");
        }
   }

   setupFinalClothQcWrapperFormDefaultValues(jsonData['items']['default']);

   wacHideBlockUI("#finalClothQcWrapperFormFormDialog");

//   wacDebugLog($.dump(jsonData));
}

function setupFinalClothQcWrapperFormDefaultValues(defaultValueObj)
{
    if(finalClothQcWrapperFormInputMode == wacFormInputMode.add)   // use default values
    {
        $("#finalClothQcWrapperForm_id").attr("value", 0);
        $('#finalClothQcWrapperForm_dispatch_order_id').flexbox(BASE_URL + 'dispatchOrder/GetIdCodeHashInFormat/status/audited/type/4?data_format=jsonFlexbox', {
            //            resultTemplate: '<div class="col1">{id}</div><div class="col2">{name}</div>',
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "dispatch_order_id",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });

        $("#finalClothQcWrapperForm_piece_length_unit_code option:[value='"+ defaultValueObj.piece_length_unit_code +"']").attr('selected', 'selected');
        $("#finalClothQcWrapperForm_roll_unit_code option:[value='"+ defaultValueObj.roll_unit_code +"']").attr('selected', 'selected');
    }
    else  // use edit obj values
    {
        $("#finalClothQcWrapperForm_id").attr("value", finalClothQcWrapperFormObj.id);  // setup id

        $('#finalClothQcWrapperForm_dispatch_order_id').flexbox(BASE_URL + 'dispatchOrder/GetIdCodeHashInFormat/status/audited/type/4?data_format=jsonFlexbox', {
            //            resultTemplate: '<div class="col1">{id}</div><div class="col2">{name}</div>',
            initialValue: finalClothQcWrapperFormObj.dispatch_order_id,
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "dispatch_order_id",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });
        $('#finalClothQcWrapperForm_dispatch_order_id_input').val(finalClothQcWrapperFormObj.dispatch_order_code);

        $("#finalClothQcWrapperForm_roll_unit_code option:[value='"+ finalClothQcWrapperFormObj.roll_unit_code +"']").attr('selected', 'selected');
        $("#finalClothQcWrapperForm_piece_length_unit_code option:[value='"+ finalClothQcWrapperFormObj.piece_length_unit_code +"']").attr('selected', 'selected');
        $("#finalClothQcWrapperForm_wrap_id option:[value='"+ finalClothQcWrapperFormObj.wrap_id +"']").attr('selected', 'selected');

        $("#finalClothQcWrapperForm_code").attr("value", finalClothQcWrapperFormObj.code);
        $("#finalClothQcWrapperForm_qc_date").attr("value", finalClothQcWrapperFormObj.qc_date);
        $("#finalClothQcWrapperForm_dispatch_date").attr("value", finalClothQcWrapperFormObj.dispatch_date);
        $("#finalClothQcWrapperForm_goods_return_date").attr("value", finalClothQcWrapperFormObj.goods_return_date);
        $("#finalClothQcWrapperForm_roll").attr("value", finalClothQcWrapperFormObj.roll);
        $("#finalClothQcWrapperForm_piece_length").attr("value", finalClothQcWrapperFormObj.piece_length);

        $("#finalClothQcWrapperForm_standard").attr("value", finalClothQcWrapperFormObj.standard);
        $("#finalClothQcWrapperForm_label_requirement").attr("value", finalClothQcWrapperFormObj.label_requirement);
        $("#finalClothQcWrapperForm_item1").attr("value", finalClothQcWrapperFormObj.item1);
        $("#finalClothQcWrapperForm_item2").attr("value", finalClothQcWrapperFormObj.item2);
        $("#finalClothQcWrapperForm_item3").attr("value", finalClothQcWrapperFormObj.item3);
        $("#finalClothQcWrapperForm_level").attr("value", finalClothQcWrapperFormObj.level);
        $("#finalClothQcWrapperForm_label_memo").attr("value", finalClothQcWrapperFormObj.label_memo);
        $("#finalClothQcWrapperForm_memo").attr("value", finalClothQcWrapperFormObj.memo);
    }

//    wacDebugLog($.dump(finalClothQcWrapperFormObj));
//    wacDebugLog($.dump(defaultValueObj));
//    wacDebugLog("finalClothQcWrapperFormInputMode: " + finalClothQcWrapperFormInputMode);

}
/***** init section, end *****/


/**************  interaction section, begin  ***************/
// audit class
function FinalClothQcWrapperFormAuditAction(){
    this.run = function(orderId){
        finalClothQcWrapperFormAudit(orderId);
    }
}

function finalClothQcWrapperFormAudit(orderId)
{
    wacShowBlockUILoading();
    var params = {
        "data_format" : 'json',
        "final_cloth_qc_wrapper_form_id" : orderId
    };
//    finalClothQcWrapperFormObj = $("#finalClothQcWrapperFormList").getRowData(orderId);
//    console.log($.dump(finalClothQcWrapperFormObj));

    $.ajax({
        url: BASE_URL + "finalClothQcWrapperForm/audit",
        global: true,
        type: "GET",
        data: params,
        dataType: "json",
        success: function(jsonData){
            finalClothQcWrapperFormAuditCallBack(jsonData);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            wacDebugLog("getFormData Error: " + $(this).dump()); // the options for this ajax request
        }
    });
}

function finalClothQcWrapperFormAuditCallBack(jsonData)
{
   if(jsonData.info.status == wacOperationStatus.Error)
   {
       wacShowTips(jsonData.info.error_info);
   }
   else
   {
       wacShowTips(jsonData.info.tips);
       $("#finalClothQcWrapperFormList").trigger("reloadGrid");
   }
   wacHideBlockUI();
//   wacDebugLog($.dump(jsonData));
}

function finalClothQcWrapperFormOpenModuleForm(moduleFormName, moduleName, inputMode, rowid)
{
    finalClothQcWrapperFormInputMode = inputMode;

    if(rowid === undefined){
        finalClothQcWrapperFormObj = {};
    }
    else
    {
        finalClothQcWrapperFormObj = $("#" + moduleName +"List").getRowData(rowid);
    }

    $('#'+moduleFormName).dialog('open');
}

function validateFinalClothQcWrapperForm()
{
    var validateFlag = true;

    if (!$("#finalClothQcWrapperFormForm").validationEngine({returnIsValid:true}))
    {
        validateFlag = false;
        return validateFlag;
    }
    

    return validateFlag;
}

function submitFinalClothQcWrapperForm()
{
    if(!validateFinalClothQcWrapperForm()){
        return;
    }

    wacShowBlockUILoading("#finalClothQcWrapperFormFormDialog", "处理中...");

    var extraParams = "data_format=json";
    var submitUrl;

    if(finalClothQcWrapperFormInputMode == wacFormInputMode.add){
        submitUrl = BASE_URL + "finalClothQcWrapperForm/add";
    }
    else{
        submitUrl = BASE_URL + "finalClothQcWrapperForm/edit";
    }


    $.ajax({
        url: submitUrl,
//        url: BASE_URL + "test/ajaxTest" ,
        global: true,
        type: "GET",
        data: $("#finalClothQcWrapperFormForm").serialize() + "&" + extraParams,
        dataType: "json",
        success: function(jsonData){
            submitFinalClothQcWrapperFormCallBack(jsonData);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            wacDebugLog("getFormData Error: " + $(this).dump()); // the options for this ajax request
        }
    });
}

function submitFinalClothQcWrapperFormCallBack(jsonData)
{
   if(jsonData.info.status == wacOperationStatus.Error)
   {
       wacShowTips(jsonData.info.error_info);
   }
   else
   {
       wacShowTips(jsonData.info.tips);
       $("#finalClothQcWrapperFormList").trigger("reloadGrid");
       $("#finalClothQcWrapperFormFormDialog").dialog('close');
   }

   wacHideBlockUI("#finalClothQcWrapperFormFormDialog");

//   wacDebugLog($.dump(jsonData));
}

/**************  interaction section, end  ***************/